<template>
  <div style="height: 100%"  ref="scrollContainer">
    <div v-for="item in logList" v-html="item"></div>
    <div :id="'bottom' + props.data['ID']"></div>
  </div>
</template>
<script setup>
import { onBeforeUnmount, onMounted, nextTick, ref } from 'vue';
import { getDockerLogs } from '@/api/docker';
import { AnsiUp } from 'ansi_up';
const logList = ref([]);
const props = defineProps({
  data: null,
});
let interval = null;
let logInterval = null;
let time = '';
// 创建 ansi_up 实例
const ansi_up = new AnsiUp();
const scrollContainer = ref(null); // 引用滚动容器

/**
 * 获取日志
 * @param first
 * @returns {Promise<void>}
 */
const getLogs = async first => {
  const { data } = await getDockerLogs(props.data['ID'], { time: time });
  if (data['logList'] === null || data['logList'].length === 0) {
    return;
  }
  time = data.time;
  let isDown = false;
  if (logList.value.length === 0) {
    isDown = true;
  }
  const element = scrollContainer.value;
  if (element) {
    if (element.scrollHeight - element.scrollTop <= 500) {
      isDown = true;
    }
  }
  if (logList.value.length === 1 && logList.value[0] === "无日志"){
    logList.value = []
  }
  await autoLogInfo(data['logList'], 3000, isDown || first);
};

/**
 * 自动获取日志
 * @param lList
 * @param t
 * @param isDown
 * @returns {Promise<void>}
 */
const autoLogInfo = async (lList, t, isDown) => {
  if (lList.length) {
    const len = lList.length;
    let nCount = 0;
    logInterval = setInterval(() => {
      logList.value.push(ansi_up.ansi_to_html(lList[nCount]));
      if (isDown)
        nextTick(() => {
          document
            .getElementById('bottom' + props.data['ID'])
            ?.scrollIntoView({ block: 'end' });
        });
      nCount++;
      if (nCount === lList.length) {
        clearInterval(logInterval);
      }
    }, t / len);
  }
};

// 定时器
interval = setInterval(() => {
  getLogs(false);
  if (logList.value.length===0){
    logList.value.push("无日志")
  }
}, 5000);

onBeforeUnmount(() => {
  // 在组件销毁前清除定时器
  clearInterval(interval);
});

onMounted(() => {
  getLogs(true);
});
</script>
<style lang="scss"></style>
